export function listToTree(list = [], root = null, idField = 'id', parentIdField = 'parentId') {
    const tree = [];
    const hash = {};
    const childrenField = 'children';
    for (let i = 0, l = list.length; i < l; i++) {
        const d = list[i];
        hash[d[idField]] = d;
    }

    for (let i = 0, l = list.length; i < l; i++) {
        const d = list[i];
        const parentID = d[parentIdField];
        if (parentID === '' || parentID === 0 || parentID === null) {
            tree.push(d);
            continue;
        }

        const parent = hash[parentID];
        if (!parent) {
            tree.push(d);
            continue;
        }

        let children = parent[childrenField];
        if (!children) {
            children = [];
            parent[childrenField] = children;
        }
        children.push(d);
    }

    if (root) {
        root[childrenField] = tree;
        return [root];
    }

    return tree;
};

export  function treeToList(tree = [], idValue = null, childrenField = 'children', idField = 'id', parentIdField = 'parentId') {
    const list = [];
    if (!childrenField) childrenField = 'children';
    for (let i = 0, j = tree.length; i < j; i++) {
        const d = tree[i];
        const id = d[idField];
        if (!list.some(l => l[idField] === id)) {
            list.push(d);
        }
        if (parentIdField) d[parentIdField] = idValue;
        const children = d[childrenField];
        if (children && children.length > 0) {
            const items = treeToList(children, id, childrenField, idField, parentIdField);
            const values = items.values();
            for (const v of values) {
                if (!list.some(l => l[idField] === v[idField])) {
                    list.push(v);
                }
            }
        }
    }
    return list;
};

	/**
	 * 获取任意时间
	 */
export	function GetAnyDate(date, AddDayCount = 0) {
		if (!date) {
			date = new Date()
		}
		if (typeof date !== 'object') {
			date = date.replace(/-/g, '/')
		}
		const dd = new Date(date)

		dd.setDate(dd.getDate() + AddDayCount) // 获取AddDayCount天后的日期

		const y = dd.getFullYear()
		const m = dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1 // 获取当前月份的日期，不足10补0
		const d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate() // 获取当前几号，不足10补0
		return {
			fullDate: y + '-' + m + '-' + d,
			year: y,
			month: m,
			date: d,
			day: dd.getDay()
		}
	}